package servlet;

import controller.ControllerLoginLocal;
import eccezioni.UtenteBannatoException;
import eccezioni.UtenteNonTrovatoException;
import eccezioni.UtenteNonVerificatoException;
import entity.Adesione;
import entity.UtenteRegistrato;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import statefulSB.UtenteLoggato.StatoIscrizione;
import statefulSB.UtenteLoggatoLocal;
import utilities.Utilities;

/**
 * Servlet che fornisce le operazini di login e logout.
 * Il login è fornito direttamente sul sito o attraverso OpenId (in questo 
 * caso la richiesta verrà rediretta verso la servlet {@link OpenIdServlet}).
 * @author Ale
 */
public class LogInOutServlet extends HttpServlet {

    @EJB
    private ControllerLoginLocal controllerLogin;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        if (action == null) {
            Utilities.errore("Nessuna action specificata alla LogInOutServlet", request, response);
        } else if (action.equals("mostraLoginPopup")) { // richiesta ajax
            mostraLoginPopup(request, response);
        } else if (action.equals("loginSito")) {
            loginSito(request, response);
        } else if (action.equals("loginOpenId")) {
            loginOpenId(request, response);
        } else if (action.equals("logout")) {
            logout(request, response);
        }
    }

    private void mostraLoginPopup(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Utilities.forward("/WEB-INF/jspf/login.jsp", request, response);
    }

    // richiesta ajax
    private void loginSito(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String mail = request.getParameter("mail");
        String pwd = request.getParameter("password");

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");

        try {
            UtenteRegistrato ur = controllerLogin.login(mail, pwd);
            UtenteLoggatoLocal ull = lookupUtenteLoggatoLocal();
            ull.setIdUtente(ur.getId());
            ull.setAdesioniInCorso(new LinkedList<Adesione>());
            ull.setStatoIscrizione(StatoIscrizione.NESSUNO);
            HttpSession session = request.getSession();
            session.setAttribute("utenteLoggato", ull);

            if (ur.isCollegatoFb()) {
                response.getWriter().write("<loginOk>linkFb</loginOk>");
            } else {
                response.getWriter().write("<loginOk>noLinkFb</loginOk>");
            }
        } catch (UtenteNonTrovatoException unte) {
            response.getWriter().write("<loginOk>"+unte.getMessage()+"</loginOk>");
        } catch (UtenteBannatoException ube) {
            response.getWriter().write("<loginOk>"+ube.getMessage()+".</loginOk>");
        } catch (UtenteNonVerificatoException unve) {
            response.getWriter().write("<loginOk>" + unve.getMessage() + "</loginOk>");
        }
    }

    // ajax
    private void loginOpenId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String mail = (String) request.getAttribute("mail");
        if (mail == null) {
            // devo ancora fare l'autenticazione OpenId
            Utilities.forward("/Controller?action=reallyLoginOpenId", request, response);
        } else {
            try {
                UtenteRegistrato ur = controllerLogin.loginOpenId(mail);
                UtenteLoggatoLocal ull = lookupUtenteLoggatoLocal();
                ull.setIdUtente(ur.getId());
                ull.setAdesioniInCorso(new LinkedList<Adesione>());
                ull.setStatoIscrizione(StatoIscrizione.NESSUNO);
                HttpSession session = request.getSession();
                session.setAttribute("utenteLoggato", ull);
                if (ur.isCollegatoFb()) {
                    Utilities.forward("/Controller?action=linkFb&redirect=http://localhost:8080/ShippingShareBisBis-war/index.jsp", request, response);
                } else {
                    response.sendRedirect("index.jsp");
                }
            } catch (UtenteNonTrovatoException unte) {
                Utilities.errore(unte.getMessage(), request, response);
            } catch (UtenteBannatoException ube) {
                Utilities.errore(ube.getMessage(), request, response);
            } catch (UtenteNonVerificatoException unve) {
                Utilities.errore(unve.getMessage(), request, response);
            }
        }
    }

    // richiesta ajax
    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UtenteLoggatoLocal ull = Utilities.getUtenteLoggatoLocal(request);
        ull.remove();
        HttpSession session = request.getSession();
        session.setAttribute("utenteLoggato", null);
        session.invalidate();
    }

    private UtenteLoggatoLocal lookupUtenteLoggatoLocal() {
        Context c;

        try {
            c = new InitialContext();
            return (UtenteLoggatoLocal) c.lookup("java:global/ShippingShareBisBis/ShippingShareBisBis-ejb/UtenteLoggato!statefulSB.UtenteLoggatoLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
